import { defineStore } from 'pinia'
import { ref } from 'vue'
import SockJS from 'sockjs-client'
import Stomp from 'stompjs'

export const useWebsocketStore = defineStore('websocket', () => {
  // ===== state =====
  const url = ref('')
  const checkInterval = ref(null)
  const websocket = ref(null)
  const stompClient = ref(null)
  const listenerList = ref([])
  // 【新增】每个 topic 对应的订阅对象
  const subscriptions = ref({}) // { [topic]: subscription }

  // ===== getters =====
  const getStompClient = () => stompClient.value

  // ===== 初始化 WebSocket 入口 =====
  const websocketInit = (_url) => {
    if (!_url && !url.value) {
      console.warn('请提供 WebSocket 连接地址')
      return
    }
    url.value = _url || url.value

    if (!stompClient.value || !stompClient.value.connected) {
      if (stompClient.value && websocket.value?.readyState === SockJS.OPEN) {
        stompClient.value.disconnect(() => {
          websocketConnect()
        })
      } else if (stompClient.value && websocket.value?.readyState === SockJS.CONNECTING) {
        console.log('连接正在建立')
        return
      } else {
        websocketConnect()
      }

      // 定时检测连接状态
      if (!checkInterval.value) {
        const interval = setInterval(() => {
          console.log('检测连接：' + websocket.value?.readyState)
          if (stompClient.value && stompClient.value.connected) {
            clearInterval(checkInterval.value)
            checkInterval.value = null
            console.log('重连成功')
          } else if (stompClient.value && websocket.value?.readyState !== SockJS.CONNECTING) {
            stompClient.value.disconnect(() => {
              websocketConnect()
            })
          }
        }, 2000)
        checkInterval.value = interval
      }
    } else {
      console.log('连接已建立成功，不再执行')
    }
  }

  // ===== 建立 WebSocket 连接并订阅历史 listenerList =====
  const websocketConnect = () => {
    const websock = new SockJS(url.value)
    websocket.value = websock
    const stomp = Stomp.over(websock)
    stomp.debug = null
    stomp.heartbeat.outgoing = 20000
    stomp.heartbeat.incoming = 0

    stomp.connect(
      { name: 'test' },
      () => {
        console.log('连接成功！')
        // 补发所有缓存的订阅（连接前的）
        listenerList.value.forEach((item) => {
          const sub = stomp.subscribe(item.topic, item.callback)
          subscriptions.value[item.topic] = sub
        })
        listenerList.value = []
      },
      () => {
        setTimeout(() => {
          websocketInit(url.value)
        }, 1000)
      }
    )
    stompClient.value = stomp
  }

  // ===== 发送消息 =====
  const websocketSend = ({ topic, data }) => {
    stompClient.value?.send(topic, {}, data)
  }

  // ===== 添加订阅（并保存 subscription）=====
  const websocketSubscribe = (topic, callback) => {
    // 已订阅过就不重复订阅
    if (subscriptions.value[topic]) return

    if (stompClient.value && stompClient.value.connected) {
      const sub = stompClient.value.subscribe(topic, callback)
      subscriptions.value[topic] = sub
    } else {
      // 未连接时，缓存下来，待连接后批量订阅
      listenerList.value.push({ topic, callback })
    }
  }

  // ===== 取消订阅（根据 topic）=====
  const websocketUnsubscribe = (topic) => {
    const sub = subscriptions.value[topic]
    if (sub) {
      sub.unsubscribe()
      delete subscriptions.value[topic]
    }
  }

  return {
    url,
    checkInterval,
    websocket,
    stompClient,
    listenerList,
    subscriptions,
    getStompClient,
    websocketInit,
    websocketConnect,
    websocketSend,
    websocketSubscribe,
    websocketUnsubscribe
  }
})
